// pages/buys/releaseInfo/releaseInfo.js
const app = getApp();
var i = 0;
let arrayLet = [],
  lengthUnitArrayLet = [],
  widthUnitArrayLet = [],
  thicknessUnitArrayLet = [],
  numUnitArrayLet = [];
Page({

  /**
   * 页面的初始数据
   */
  data: {
    array: ['一级', '二级', '三级', '四级'],
    index: '0',
    thicknessUnitIndex: '0',
    lengthUnitIndex: '0',
    numUnitIndex: '0',
    widthUnitIndex:'0',
    widthUnitArray: app.globalData.lenthUnit,
    thicknessUnitArray: app.globalData.lenthUnit,
    numUnitArray: app.globalData.quantityUnit,
    // lengthUnitArray: app.globalData.lenthUnit,
    date: "1992-10-12",
    url: 'buyerpurinfo/releaseBuyInfo',
    uploaderList: [],
    uploaderNum: 0,
    showUpload: true,
    allImgSrc: "",
    maxInputLength:15,
    userInfo:{},
    openId : "",
    unitUrl: "dictionary/queryDictionaryById",
    product_req:"",
    orders:{},
    buyId:"",
  },
  /**
   * 获取表单数据
   */
  submitData: function(event) {
    var that = this;
    console.log("提交表单：",event.detail.value)
    var form_data = event.detail.value;
    var flag = that.verifyForm(form_data);
    if(!flag){
      return ;
    }
    i = 0;
    that.setData({
      allImgSrc: ""
    });
    
    console.log("图片数量" + that.data.uploaderList.length)
    if (that.data.uploaderList.length > 0) {
      that.toReleaseBuyInfoForImg(form_data);
    } else {
      that.toReleaseBuyInfo(form_data);
    }


    // wx.showToast({
    //   title: '数据修改成功',
    // })
  },
  //输入简介
  describeInput: function (e) {
    var that = this;
    var data = that.data.product_req;
    data = e.detail.value;
    that.setData({
      product_req: data,
    })
  },

  verNum:function(data,name){
    var regNum = new RegExp('[0-9]', 'g');
    if (!regNum.exec(data)) {
      wx.showToast({
        title: name+'请输入数字',
        icon: 'none',
      })
      return false;
    }
    return true;
  },


  verifyForm: function (formData){
    var that = this;
    var form_data = formData;

    
    if (!form_data.product_name){
      wx.showToast({
          title: '请输入品名',
          icon:'none',
      }) 
      return false;
    }
    if (!form_data.product_length) {
      
      wx.showToast({
        title: '请输入长度',
        icon: 'none',
      })
      return false;
    }
    // else{
    //   if(!that.verNum(form_data.product_length,"长度")){
    //     return false;
    //   }
    // }


    if (!form_data.product_thickness) {
      wx.showToast({
        title: '请输入厚度',
        icon: 'none',
      })
      return false;
    }
    // if (!form_data.product_level) {
    //   wx.showToast({
    //     title: '请输入等级',
    //     icon: 'none',
    //   })
    //   return false;
    // }

    if (!form_data.inten_price) {
      wx.showToast({
        title: '请输入意向价格',
        icon: 'none',
      })
      return false;
    }
    if (!form_data.num) {
      wx.showToast({
        title: '请输入数量',
        icon: 'none',
      })
      return false;
    }
    if (!form_data.phone) {
      wx.showToast({
        title: '请输入联系电话',
        icon: 'none',
      })
      return false;
    }
    return true;
  },

  toReleaseBuyInfo: function(data) {
    var that = this;
    data.openId = that.data.openId;
    data.id = that.data.buyId;
    data.product_level = that.data.array[that.data.index];
    data.length_unit = that.data.lengthUnitArray[that.data.lengthUnitIndex];
    data.width_unit = that.data.widthUnitArray[that.data.widthUnitIndex];
    data.thickness_unit = that.data.thicknessUnitArray[that.data.thicknessUnitIndex];
    data.num_unit = that.data.numUnitArray[that.data.numUnitIndex];
    data.product_req = that.data.product_req;
    app.post(that.data.url, data).then((res) => {
      console.log('success');
      console.log(res);
      if (res.code == 1) {
        // wx.showToast({
        //   title: '发布信息成功',
        // })
        wx.showModal({
          title: '提示',
          content: '提交成功!',
          showCancel: false,
          success: function (res) {
            wx.navigateBack({
              delta: 2
            })
          }
        })
      } else {
        wx.showModal({
          title: '温馨提示',
          content: res.msg,
          showCancel: false,
        })
      }

    }).catch((errMsg) => {
      console.log('fail');
      console.log(errMsg + '失败');
    })
  },


  toReleaseBuyInfoForImg: function(form_data) {
    console.log(form_data);
    var that = this;
    wx.uploadFile({
      url: app.globalData.requestURL +'buyerpurinfo/releaseBuyInfoImg',
      filePath: that.data.uploaderList[i],
      name: 'image',
      success: function(res) {
        i++;
        console.log(res);
        var result = JSON.parse(res.data);

        if (result.code == 1) {
          if (i == that.data.uploaderList.length) {
            that.setData({
              allImgSrc: that.data.allImgSrc + "," + result.data
            })
            var buy_data = form_data;
            buy_data.imgSrc = that.data.allImgSrc;
            that.toReleaseBuyInfo(buy_data);
            i = 0;
          } else if (i < that.data.uploaderList.length) {
            that.setData({
              allImgSrc: that.data.allImgSrc + "," + result.data
            })
            that.toReleaseBuyInfoForImg(form_data);
           
          }

        }
      }
    })
  },


  /**
   * 等级
   */
  bindIndustryChange: function(event) {
    this.setData({
      index: event.detail.value
    })

  },
  /**
   * 长度单位
   */
  bindLengthUnitChange: function (event) {
    var that = this;
    if(event.currentTarget.id=="1"){
      that.setData({
        lengthUnitIndex: event.detail.value
      })
    } else if (event.currentTarget.id == "2"){
      that.setData({
        widthUnitIndex : event.detail.value
      })
    } else if (event.currentTarget.id == "3") {
      that.setData({
        thicknessUnitIndex: event.detail.value
      })
    }else{
      console.log("为匹配到单位")
    }
    
  },
  /**
   * 数量单位
   */
  bindNumUnitChange:  function(event) {
    this.setData({
      numUnitIndex: event.detail.value
    })
  },
  /**
   * 获取日期数据
   */
  bindDateChange: function(event) {
    this.setData({
      date: event.detail.value
    })
  },
  // 删除图片
  clearImg: function(e) {
    var nowList = []; //新数据
    var uploaderList = this.data.uploaderList; //原数据

    for (let i = 0; i < uploaderList.length; i++) {
      if (i == e.currentTarget.dataset.index) {
        continue;
      } else {
        nowList.push(uploaderList[i])
      }
    }
    this.setData({
      uploaderNum: this.data.uploaderNum - 1,
      uploaderList: nowList,
      showUpload: true
    })
  },
  //展示图片
  showImg: function(e) {
    var that = this;
    wx.previewImage({
      urls: that.data.uploaderList,
      current: that.data.uploaderList[e.currentTarget.dataset.index]
    })
  },
  //上传图片
  upload: function(e) {
    var that = this;
    wx.chooseImage({
      count: 9 - that.data.uploaderNum, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function(res) {
        console.log(res)
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        let tempFilePaths = res.tempFilePaths;
        let uploaderList = that.data.uploaderList.concat(tempFilePaths);
        if (uploaderList.length == 9) {
          that.setData({
            showUpload: false
          })
        }
        that.setData({
          uploaderList: uploaderList,
          uploaderNum: uploaderList.length,
        })
      }
    })
  },

  findArrayIndex: function (object, array){
    for(var i=0;i<array.length;i++){
      if(array[i]==object){
        return i;
      }
    }
    return 0;
  },

  initImfo:function(id){
    var that = this;
    app.post("buyerpurinfo/queryBuyerInfoById", {'id':id}).then((res) => {
      console.log('initImfo success');
      console.log(res);
      if (res.code == 0) {
        // wx.showToast({
        //   title: '发布信息成功',
        // })
        var lengthUnitIndex = that.findArrayIndex(res.resultData.length_unit, that.data.lengthUnitArray);
        var widthUnitIndex = that.findArrayIndex(res.resultData.width_unit, that.data.widthUnitArray);
        var thicknessUnitIndex = that.findArrayIndex(res.resultData.thickness_unit, that.data.thicknessUnitArray);
        var numUnitIndex = that.findArrayIndex(res.resultData.num_unit, that.data.numUnitArray);
        var index = that.findArrayIndex(res.resultData.product_level, that.data.array) 

        that.setData({
          orders: res.resultData,
          product_req: res.resultData.product_req,
          buyId: res.resultData.id,
          index: res.resultData.product_level,
          lengthUnitIndex: lengthUnitIndex,
          widthUnitIndex: widthUnitIndex,
          thicknessUnitIndex: thicknessUnitIndex,
          numUnitIndex: numUnitIndex,
          index: index,
        })
        console.log(that.data);
      } else {
        wx.showModal({
          title: '温馨提示',
          content: res.msg,
          showCancel: false,
        })
      }

    }).catch((errMsg) => {
      console.log('fail');
      console.log(errMsg + '失败');
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    console.log("releaseInfo页面初始化加载", options)
    var that = this;
    if (wx.getStorageSync('userInfo')) {
      that.setData({
        userInfo: wx.getStorageSync('userInfo'),//获取用户信息
        openId: wx.getStorageSync('userInfo').userId
      })
    }
    console.log(that.data.userInfo);
    lengthUnitArrayLet = [];
    numUnitArrayLet = [];
    arrayLet = [];
    widthUnitArrayLet = [],
    thicknessUnitArrayLet = [],

    app.post(that.data.unitUrl, { dtId:"general_unit"}).then((res) => {
      console.log('success');
      console.log(res);
      if (res.code == 0) {
        res.resultData.forEach(function (rect) {
          //console.log(rect)
          if (rect.sd_code =="length_unit"){
            lengthUnitArrayLet.push(rect.sd_value_1);
          } else if (rect.sd_code == "num_unit") {
            numUnitArrayLet.push(rect.sd_value_1);
          } else if (rect.sd_code == "level_unit") {
            arrayLet.push(rect.sd_value_1);
          } else if (rect.sd_code == "width_unit") {
            widthUnitArrayLet.push(rect.sd_value_1);
          } else if (rect.sd_code == "thickness_unit") {
            thicknessUnitArrayLet.push(rect.sd_value_1);
          }else{
            console.log("未查询到匹配项")
          }
        });
        if (arrayLet.length!=0){
          that.setData({
            array: arrayLet,
          });
        }
        if (lengthUnitArrayLet.length != 0) {
          that.setData({
            lengthUnitArray: lengthUnitArrayLet,
          });
        }
        if (widthUnitArrayLet.length != 0) {
          that.setData({
            widthUnitArray: widthUnitArrayLet,
          });
        }
        if (thicknessUnitArrayLet.length != 0) {
          that.setData({
            thicknessUnitArray: thicknessUnitArrayLet,
          });
        }
        if (numUnitArrayLet.length != 0) {
          that.setData({
            numUnitArray: numUnitArrayLet,
          });
        }

        if (options.buyId) {
          that.initImfo(options.buyId);
        }
      } else {
        wx.showModal({
          title: '温馨提示',
          content: res.msg,
          showCancel: false,
        })
      }

    }).catch((errMsg) => {
      console.log('fail');
      console.log(errMsg + '失败');
    })

    that.setData({
      allImgSrc: ""
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})